package com.wzh.test.binarytree;

import java.util.Arrays;

public class HeapSortDemo {
    public static void main(String[] args) {
        int[] arr = {4, 6, 5, 9, 8};
        //最后一课子树的下标k=5/2 - 1 = 1
        //前一颗树的下表k=k/2 - 1 = 0
        for (int length = arr.length; length > 1; length--) {
            for (int k = length / 2 - 1; k >= 0; k--) {
                convertABigTopHeapTree(arr, length, k);
                int temp = arr[0];
                arr[0] = arr[length - 1];
                arr[length - 1] = temp;
            }
        }

        System.out.println(Arrays.toString(arr));
    }


    public static void convertABigTopHeapTree(int[] arr, int length, int treeRootIndex) {
        for (int k = treeRootIndex; k <= length / 2 - 1; k = k * 2 + 1) {
            int temp = arr[k];

            int leftIndex = k * 2 + 1;
            int bigChildIndex = leftIndex;
            int rightIndex = leftIndex + 1;
            if (rightIndex < length && arr[leftIndex] < arr[rightIndex]) {
                bigChildIndex = rightIndex;
            }
            if (arr[k] < arr[bigChildIndex]) {
                //交换
                arr[k] = arr[bigChildIndex];
                arr[bigChildIndex] = temp;
                k = bigChildIndex;
            } else {
                break;
            }

        }
    }
}
